<?php
namespace app\home\logic;

use app\common\logic\Base;
use think\Db;
use think\facade\App;
use think\facade\Request;

class UrlChannel extends  Base {
    
    /**
     * @desc 我的渠道
     * @param array $params
     * @param int $userId
     * @return array
     * @throws \Exception
     */
    public function index($params, $userId) {
        $where[] = ['uc_user_id', '=', $userId];
        if($params['channelName']) {
            $where[] = ['uc_channel_name', 'like', $params['channelName'].'%'];
        }

        if($params['channelKey']) {
            $where[] = ['uc_channel_key', '=', $params['channelKey']];
        }

        if($params['channelCode']) {
            $where[] = ['uc_channel_code', 'like', $params['channelCode'].'%'];
        }

        if($params['startDate'] && $params['endDate']) {
            $startTime = date('Y-m-d 00:00:00', strtotime($params['startDate']));
            $endTime = date('Y-m-d 23:59:59', strtotime($params['endDate']));
            $where[] = ['uc_create_time', 'between', [$startTime, $endTime]];
        }else{
            if($params['startDate']) {
                $where[] = ['uc_create_time', 'gt', date('Y-m-d 00:00:00', strtotime($params['startDate']))];
            }
            if($params['endDate']) {
                $where[] = ['uc_create_time', 'lt', date('Y-m-d 23:59:59', strtotime($params['endDate']))];
            }
        }

        if(isset($params['status']) && $params['status'] != '') {
            $where[] = ['uc_status', '=', $params['status']];
        }

        $list = App::model('UrlChannel')
            ->where($where)
            ->order('uc_channel_id', 'desc')
            ->paginate($params['pageSize'], false, ['query' => request()->param()]);

        $pagination = $list->render();
        $domainUrl = model('Domain')->getDomain($userId);
        if($list) {
            $list = $list->toArray();
            $list = output_format($list['data'], 'uc');

            $channelIds = array_column($list, 'channelId');
            $urlInfo = model('UrlChannelRelation')
                ->where('ucr_channel_id', 'in', $channelIds)
                ->leftJoin('Url', 'url_id = ucr_url_id')
                ->column('keyword', 'ucr_channel_id');

            foreach ($list as $k => $v) {
                $list[$k]['count'] = model('UrlChannelRelation')
                    ->where('ucr_channel_id', '=', $v['channelId'])
                    ->count();
                $list[$k]['keyword'] = $urlInfo[$v['channelId']];
            }
        }
        return [
            'list'       => $list,
            'params'     => $params,
            'domainUrl'  => $domainUrl,
            'pagination' => $pagination
        ];
    }

    /**
     * @desc 编辑
     * @param $channelId
     * @param $userId
     * @return array
     * @throws \think\Exception
     */
    public function edit($channelId,$userId) {
        $where = [
            'uc_channel_id' => $channelId,
            'uc_user_id'  => $userId
        ];
        $info = model('UrlChannel')
            ->where($where)
            ->find();

        return [
            'info' => $info ?output_format($info, 'uc'): 0
        ];
    }

    /**
     * @desc 编辑链接
     * @param array $params
     * @param int $userId
     * @return bool
     * @throws \Exception
     */
    public function operateAjax($params, $userId) {
        $data = [
            'uc_user_id'       => $userId,
            'uc_channel_name'  => $params['channelName'],
            'uc_params_switch' => $params['paramsSwitch'],
            'uc_channel_key'   => $params['channelKey'],
            'uc_channel_code'  => $params['channelCode'],
            'uc_status'        => $params['status'],
            'uc_remark'        => $params['remark'],
            'uc_modify_time'   => date('Y-m-d H:i:s')
        ];
        $data = array_filter($data, function($arr) {
            if($arr === '' || $arr === null) {
                return false;
            }
            return true;
        });
        
        if($params['action'] == 'add') {
            $data['uc_create_time'] = date('Y-m-d H:i:s');
            $result = model('UrlChannel')->insertGetId($data);
        }else {
            $Where = [
                'uc_user_id' => $userId,
                'uc_channel_id'      => $params['id'],
            ];
            $groupInfo = model('UrlChannel')->where($Where)->find();
            if(!$groupInfo) {
                $this->errorCode = EC_HOME_URL_GROUP_NOT_EXIST;
                return false;
            }
            $result = model('UrlChannel')
                ->where($Where)
                ->update($data);
        }
        
        if($result === false) {
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
        return true;
    }

    /**
     * @desc 批量添加
     * @param int $userId
     * @return array
     */
    public function batchAdd($userId) {
        //获取用户配置的域名
        $domainUrl = model('Domain')->getDomain($userId);
        $keyword = model('Url')->getUrlKeyword(5);
        return [
            'domainUrl'   => $domainUrl,
            'keyword'     => $keyword,
            'channelCode' => random_string(8, 'int'),
        ];
    }

    /**
     * @desc 批量添加渠道
     * @param array $params
     * @param int $userId
     * @return array|bool
     * @throws \Exception
     */
    public function batchAddAjax($params, $userId) {
        $request= Request::instance();
        $ip = $request->ip(); //获取客户端IP地址
        $header = $request->header();
        $userAgent = $header['user-agent'];

        $expireTime = date('Y-m-d H:i:s', strtotime('+20year'));
        $data = [
            'user_id'       => $userId,
            'keyword'       => $params['keyword'],
            'link'          => $params['link'],
            'link_type'     => URL_LINK_TYPE_DEFAULT,
            'user_agent'    => $userAgent,
            'ip'            => $ip,
            'expire_time'   => $expireTime ,
            'modify_time'   => date('Y-m-d H:i:s'),
            'create_time'   => date('Y-m-d H:i:s')
        ];
        $data = array_filter($data, function($arr) {
            if($arr === '' || $arr === null) {
                return false;
            }
            return true;
        });

        Db::startTrans();
        $urlId = model('Url')->insertGetId($data);
        if($urlId === false) {
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }

        $domainUrl = model('Domain')->getDomain($userId);
        $checkTrans = [];
        $insertChannelRelationData = [];
        for ($i = 0; $i < $params['channelNum']; $i++) {
            $keyword = model('Url')->getUrlKeyword(5);
            //批量生成链接
            $urlData = [
                'user_id'       => $userId,
                'keyword'       => $keyword,
                'link'          => $domainUrl.'/'.$params['keyword'], //批量生成的原始链接为主链接的短链
                'link_type'     => URL_LINK_TYPE_DEFAULT,
                'user_agent'    => $userAgent,
                'ip'            => $ip,
                'expire_time'   => $expireTime ,
                'modify_time'   => date('Y-m-d H:i:s'),
                'create_time'   => date('Y-m-d H:i:s')
            ];
            $checkTrans[] = $urlId = model('Url')->insertGetId($urlData);

            $urlChannelData = [
                'uc_user_id'       => $userId,
                'uc_channel_name'  => $params['channelName'] . str_pad($i + 1, 3, "0", STR_PAD_LEFT),
                'uc_channel_key'   => $params['channelKey'],
                'uc_channel_code'  => random_string(8, $params['channelCode']),
                'uc_status'        => $params['status'],
                'uc_params_switch' => $params['paramsSwitch'],
                'uc_remark'        => $params['remark'],
                'uc_modify_time'   => date('Y-m-d H:i:s'),
                'uc_create_time'   => date('Y-m-d H:i:s')
            ];
            $checkTrans[] = $channelId = model('UrlChannel')->insertGetId($urlChannelData);

            $insertChannelRelationData[] = [
                'ucr_url_id'      => $urlId,
                'ucr_user_id'     => $userId,
                'ucr_channel_id'  => $channelId,
                'ucr_create_time' => date('Y-m-d H:i:s')
            ];
        }
        //判断每次短链接是否插入成功
        foreach ($checkTrans as $v) {
            if($v === false) {
                Db::rollback();
                $this->errorCode = EC_DATABASE_ERROR;
                return false;
            }
        }

        $channelRelationResult = model('UrlChannelRelation')->insertAll($insertChannelRelationData);
        if($channelRelationResult) {
            Db::commit();
            return true;
        }else {
            Db::rollback();
            $this->errorCode = EC_DATABASE_ERROR;
            return false;
        }
    }
}
